<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="套餐编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入套餐编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="isDeleted">
        <el-input
          v-model="queryParams.isDeleted"
          placeholder="请输入是否删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['canteen:setmeal:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['canteen:setmeal:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['canteen:setmeal:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['canteen:setmeal:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="setmealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="状态 0:停用 1:启用" align="center" prop="status" />
      <el-table-column label="套餐编码" align="center" prop="code" />
      <el-table-column label="描述信息" align="center" prop="description" />
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['canteen:setmeal:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['canteen:setmeal:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="套餐编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入套餐编码" />
        </el-form-item>
        <el-form-item label="选择菜品" prop="description">
          <div style="display: flex; flex-wrap: wrap; gap: 6px;">
            <el-tag
              v-for="id in form.selectedDishes"
              :key="id"
              type="success"
              closable
              @close="removeSelectedDish(id)"
            >
              {{ getDishLabel(id) }}
            </el-tag>
            <el-button size="mini" @click="selectDishsVisible">选择菜品</el-button>
          </div>
        </el-form-item>
        <el-form-item label="图片" prop="image" style="">
          <image-upload v-model="form.image"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择菜品" :visible.sync="dishDialogVisible" width="800px" append-to-body>
      <div style="display: flex; height: 400px">
        <!-- 左栏：类型筛选 -->
        <div style="width: 100px; border-right: 1px solid #ebeef5;">
          <el-menu default-active="大荤" @select="handleTypeChange">
            <el-menu-item index="大荤">大荤</el-menu-item>
            <el-menu-item index="小荤">小荤</el-menu-item>
            <el-menu-item index="素菜">素菜</el-menu-item>
            <el-menu-item index="主食">主食</el-menu-item>
            <el-menu-item index="汤">特殊</el-menu-item>
            <el-menu-item index="水果">特殊</el-menu-item>
            <el-menu-item index="特殊">特殊</el-menu-item>
          </el-menu>
        </div>

        <!-- 中栏：菜品列表 -->
        <div style="flex: 1; padding: 10px; border-right: 1px solid #ebeef5;">
          <el-checkbox-group v-model="form.selectedDishes">
            <el-checkbox
              v-for="dish in filteredDishList"
              :key="dish.id"
              :label="dish.id"
              border
            >
              {{ dish.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 右栏：已选 -->
        <div style="width: 200px; padding: 10px;">
          <div v-for="dish in selectedDishes" :key="dish.id" style="margin-bottom: 5px">
            <span>{{ dish.type }} - {{ dish.name }}</span>
            <el-button type="text" icon="el-icon-close" @click="removeDish(dish.id)" />
          </div>
        </div>
      </div>

      <div slot="footer">
        <el-button type="primary" @click="confirmDishSelect">确定</el-button>
        <el-button @click="dishDialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listSetmeal, getSetmeal, delSetmeal, addSetmeal, updateSetmeal } from "@/api/canteen/setmeal";
import { getDishList } from "@/api/canteen/dish";


export default {
  name: "Setmeal",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐管理表格数据
      setmealList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        code: null,
        description: null,
        image: null,
        createUser: null,
        updateUser: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
      },
      dishDialogVisible: false,
      dishList: [], // 所有菜品
      dishTypeFilter: '大荤',
    };
  },
  created() {
    this.getList();
  },
  computed: {
    filteredDishList() {
      return this.dishList.filter(d => d.type === this.dishTypeFilter);
    },
    selectedDishes() {
      return this.dishList.filter(dish => this.form.selectedDishes.includes(dish.id));
    }
  },
  methods: {
    getDishLabel(id) {
      const dish = this.dishList.find(dish => dish.id === id);
      if (!dish) return '';
      return `${dish.type} - ${dish.name}`;
    },
    selectDishsVisible(){
      this.dishDialogVisible = true
    },
    removeSelectedDish(id) {
      this.form.selectedDishes = this.form.selectedDishes.filter(d => d !== id);
    },
    /** 查询套餐管理列表 */
    getList() {
      this.loading = true;
      listSetmeal(this.queryParams).then(response => {
        this.setmealList = response.rows;
        this.total = response.total;
        getDishList().then(response => {
          if (response.code === 200) {
            this.dishList = response.rows;
          }
        });
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.dishTypeFilter = '大荤';
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: null,
        code: null,
        description: null,
        image: null,
        isDeleted: null,
        selectedDishes: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加套餐";
      this.handleGetDishList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSetmeal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改套餐管理";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除套餐管理编号为"' + ids + '"的数据项？').then(function() {
        return delSetmeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('canteen/setmeal/export', {
        ...this.queryParams
      }, `setmeal_${new Date().getTime()}.xlsx`)
    },
    /** 处理获取菜品列表 */
    handleGetDishList() {
      getDishList().then(response => {
        if (response.code === 200) {
          this.dishList = response.rows;
        }
      });
    },
    handleTypeChange(type) {
      this.dishTypeFilter = type;
    },
    removeDish(id) {
      this.form.selectedDishes = this.form.selectedDishes.filter(d => d !== id);
    },
    confirmDishSelect() {
      this.dishDialogVisible = false;
    },
    // 清空数据（在父弹窗关闭时）
    resetDishSelection() {
      this.selectedIds = [];
      this.tempSelectedMap = {};
      this.dishTypeFilter = '大荤';
    },
  }
};
</script>

<style scoped>
.dish-name-dropdown {
  width: 200px;
}
</style>
